import axios from "axios";
import queryString from 'querystring';
import router from "@/router";
import { Message } from "element-ui";

let baseUrl = '/api';

// 请求拦截器
axios.interceptors.request.use(req => {
    req.headers.authorization = JSON.parse(sessionStorage.getItem('userInfo')) ? JSON.parse(sessionStorage.getItem('userInfo')).token : null;
    return req;
})

// 效应拦截器
axios.interceptors.response.use(res => {
    if (res.data.code == 403) {
        Message.error(res.data.msg);
        router.push('/login');
        return;
    }
    return res.data;
})

// get请求封装
export function get(url, params = {}) {
    return new Promise((reslove, reject) => {
        axios.get(baseUrl + url, { params }).then(res => {
            reslove(res);
        }).catch(err => {
            reject(err);
        });
    })
}

// post请求封装
export function post(url, params = {}, isfile = false) {
    let newData = {};
    if (isfile) {
        newData = new FormData();
        for (let key in params) {
            newData.append(key, params[key]);
        }
    } else {
        newData = queryString.stringify(params);
    }
    return new Promise((reslove, reject) => {
        axios.post(baseUrl + url, newData).then(res => {
            reslove(res);
        }).catch(err => {
            reject(err);
        });
    })
}